<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>兑换详情</h3>
    </div>
    <el-row style="margin-top: 1.5rem; width: 100%">
      <!-- <el-col :xs="24" :sm="12" :lg="6">
        <el-input placeholder="部门名称"></el-input>
      </el-col> -->
      <!-- 顶部搜索栏 -->
      <div style="width: 100%">
        <el-form :model="searchForm" ref="searchFormRef" label-width="auto">
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="手机号：" prop="queryCondition">
                <el-input placeholder="请输入手机号" v-model="searchForm.queryCondition" clearable @blur="getData"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="兑换状态：" prop="state">
                <el-select v-model="searchForm.state" placeholder="请选择兑换状态" clearable @change="getData">
                  <el-option v-for="item in cardtype" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <div class="databox">
                <label class="el-form-item__label" style="padding-left: 0.5rem">兑换时间：</label>
                <el-date-picker label="兑换时间：" v-model="datavalue1" type="datetimerange" start-placeholder="开始日期"
                  end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                  time-format="A hh:mm:ss" @change="openActiveTime" />
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-row>
    <!-- <el-row>
      <el-button type="danger">批量作废</el-button>
      <el-button type="primary">导出推广码</el-button>
    </el-row> -->
    <el-row>
      <div v-if="Number(queryParams.type) === 2" class="tips">
        <span>通用兑换码：{{ queryParams.cdkey }}</span>
        <span class="copy" @click="copyCode(queryParams.cdkey)"> 复制</span>
        <span style="margin-left: 40px">可兑换总量：{{ queryParams.issueAmount }}份</span>
        <span style="margin-left: 40px">已兑换总量：{{ queryParams.usedAmount }}份</span>
      </div>
    </el-row>
    <art-table :data="tableData" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
      @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" prop="id" width="150" align="center" />
        <!-- <el-table-column label="题目标题" prop="bankcont_title" /> -->
        <el-table-column label="兑换码" prop="cdkey" width="150px" align="center">
          <!-- <template #default="scope">
            <div class="bankcont_title">
              <div class="bankcont_title_text">{{ scope.row.cdkey }}</div>
            </div>
          </template> -->
        </el-table-column>
        <el-table-column label="兑换类型" align="center">
          <template #default="scope">
            <el-button round size="small">
              {{ Number(queryParams.type) === 1 ? '一券一码' : '通用码' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="活动名称" align="center">
          {{ queryParams.name }}
        </el-table-column>
        <el-table-column label="兑换内容" prop="actname" align="center" width="300px">
          {{ queryParams.exchangeContent }}
        </el-table-column>
        <el-table-column label="兑换状态" prop="state" align="center">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.state)">
              {{ buildTagText(scope.row.state) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="兑换时间" prop="useTime" align="center">
          <template #default="scope">
            {{ scope.row.useTime === null ? '' : formatDate(scope.row.useTime) }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="兑换用户" prop="avatar" #default="scope" v-if="columns[0].show" style="cursor: pointer">
          <div class="user" style="display: flex; align-items: center; cursor: pointer">
            <img class="avatar" :src="scope.row.avatar" style="width: 50px; height: 50px; border-radius: 50%"
              v-if="scope.row.avatar" />
            <div>
              <el-dropdown placement="top-end">
                <el-link underline="never">{{ scope.row.nickName }}</el-link>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <p>{{ scope.row.nickName }} ID:{{ scope.row.memberId }}</p>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <p class="email" v-if="scope.row.memberId">ID:{{ scope.row.memberId }}</p>
            </div>
          </div>
        </el-table-column> -->
        <el-table-column label="兑换用户" prop="avatar" #default="scope" align="center">
          <!-- <div class="user" style="display: flex; align-items: center"> -->
          <!-- <img :src="scope.row.avatar" alt="" style="width: 50px; height: 50px; border-radius: 50%"
              v-if="scope.row.avatar" /> -->
          <div style="display: flex;flex-direction: column; align-items: center">
            <p class="user-name">{{ scope.row.nickName }}</p>
            <p class="email" v-if="scope.row.memberId">ID:{{ scope.row.memberId }}</p>
            <p v-if="scope.row.memberMobile">手机号：{{ scope.row.memberMobile }}</p>
          </div>
          <!-- </div> -->
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <button-table type="edit" icon="&#xe689;" @click="buttonMoreClick(scope.row)" />
            <button-table type="delete" @click="deleteRole(scope.row.id)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增题目' : '编辑题目'" width="30%"
      v-model:visible="dialogVisible" style="height: 800px; overflow: hidden; overflow-y: auto"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" style="padding-right: 100px">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" :rows="3" />
        </el-form-item>
        <el-form-item label="车型" prop="card_type">
          <el-checkbox v-model="checked1" label="大车" size="large" />
          <el-checkbox v-model="checked2" label="小车" size="large" />
          <el-checkbox v-model="checked3" label="客车" size="large" />
        </el-form-item>
        <el-form-item label="题目名称" prop="name">
          <el-input type="textarea" :rows="4" v-model="form.name" />
        </el-form-item>
        <el-form-item label="图片" prop="name">
          <el-upload action="#" list-type="picture-card" :auto-upload="false">
            <el-icon>
              <Plus />
            </el-icon>

            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview_banner(file)">
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span v-if="!disabled_banner" class="el-upload-list__item-delete"
                    @click="handleDownload_banner(file)">
                    <el-icon>
                      <Download />
                    </el-icon>
                  </span>
                  <span v-if="!disabled_banner" class="el-upload-list__item-delete" @click="handleRemove_banner(file)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="题目类型" prop="cont_type">
          <!-- 单选 -->
          <el-radio v-model="radio" label="1" @change="showcovercont_type">单选题</el-radio>
          <el-radio v-model="radio" label="2" @change="showcovercont_type">判断题</el-radio>
        </el-form-item>
        <!-- 单选题 -->
        <div class="contlist_list" v-if="covercont_type">
          <el-form-item label="题目A："><el-input class="contliststyle" v-model="form.listone" /></el-form-item>
          <el-form-item label="题目B："><el-input class="contliststyle" v-model="form.listtwo" /></el-form-item>
          <el-form-item label="题目C："><el-input class="contliststyle" v-model="form.listthree" /></el-form-item>
          <el-form-item label="题目D："><el-input class="contliststyle" v-model="form.listfore" /></el-form-item>
        </div>
        <!-- 单选题 -->
        <!-- 判断题 -->
        <div class="contlist_list" v-if="!covercont_type">
          <el-form-item label="题目A："><el-input class="contliststyle" v-model="form.listone" /></el-form-item>
          <el-form-item label="题目B："><el-input class="contliststyle" v-model="form.listtwo" /></el-form-item>
        </div>
        <!-- end判断题 -->
        <el-form-item label="答案" prop="sort">
          <el-input v-model="form.sort" />
        </el-form-item>
        <el-form-item label="题目解析" prop="analysis">
          <el-input type="textarea" :rows="6" v-model="form.analysis" />
        </el-form-item>
        <el-form-item label="速学速记" prop="sort">
          <el-input type="textarea" :rows="6" v-model="form.sort" />
        </el-form-item>
        <el-form-item label="视频讲解" prop="video">
          <!-- 上传视频部分 -->
          <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1" accept="video/*">
            <el-icon>
              <Plus />
            </el-icon>
            <template #file="{ file }">
              <div>
                <video class="el-upload-list__item-thumbnail" :src="file.url" width="160" height="90" controls></video>
              </div>
            </template>
          </el-upload>
          <!-- 上传视频部分 -->
        </el-form-item>
        <el-form-item label="是否VIP" prop="sort">
          <el-switch v-model="isvipshowone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="promotionDialogVisible" title="推广码" width="20%" :close-on-click-modal="false">
      <div class="promotion_item">
        <div class="promotionFont">
          兑换码：{{ promotionItem.cdkey }}
        </div>
        <img :src="promotionItem.qrCode" alt="" class="promotionImg" />
        <el-button type="primary" @click="downloadQRCode">下载推广码</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ButtonMoreItem } from '@/components/core/forms/ArtButtonMore.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import type { UploadFile } from 'element-plus'
import { cdKeyDetails, DelCdKeyDetails } from '@/api/userStudentsApi'

const dialogVisible = ref(false)
const permissionDialog = ref(false)
const promotionDialogVisible = ref(false)
const router = useRouter(); // 使用useRouter获取路由实例
const datavalue1 = ref('') //创建时间：
const columns = reactive([
  { name: '用户信息', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '来源', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])
const route = useRoute()
const queryParams = route.query

const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入题库', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sort: [{ required: true, message: '请输入正确排序', trigger: 'blur' }]
})

const form = reactive({
  id: '',
  cont_type: '',
  name: '',
  des: '',
  sort: '1',
  status: true,
  listone: '',
  listtwo: '',
  listthree: '',
  listfore: '',
  analysis: ''
})
const filterTag = (value: string, row: any) => {
  return row.status === value
}

const getTagType = (status: number) => {
  switch (status) {
    case 1:
      return 'success'
    case 2:
      return 'info'
    case 3:
      return 'warning'
    case 4:
      return 'danger'
  }
}

const buildTagText = (status: number) => {
  let text = ''
  if (status === 1) {
    text = '已使用'
  } else if (status === 2) {
    text = '未使用'
  } else if (status === 3) {
    text = '已过期'
  } else {
    text = '已作废'
  }
  return text
}
const dialogType = ref('add')

interface item {
  cdkey: string
  qrCode: string
}
const promotionItem = ref<item>({
  cdkey: '',
  qrCode: ''
})
const showDialog = (type: string, row?: any) => {
  promotionDialogVisible.value = true
  promotionItem.value = row
}

const buttonMoreClick = (row: any) => {
  showDialog('edit', row)
}

const showPermissionDialog = () => {
  permissionDialog.value = true
}

const searchFormRef = ref<FormInstance>()

const changeColumn = (list: any) => {
  columns.values = list
}

const searchForm = reactive({
  queryCondition: '',
  queryStartTime: '',
  queryEndTime: '',
  state: ''
})

const deleteRole = (id: number) => {
  ElMessageBox.confirm('确定作废兑换码吗？', '作废确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await DelCdKeyDetails(id)
    if (res.code === '00000') {
      ElMessage.success('作废成功')
      getData()
    }
  })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate((valid) => {
    if (valid) {
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
      ElMessage.success(message)
      dialogVisible.value = false
      formEl.resetFields()
    }
  })
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

interface TableData {
  id: string
  membercont: string
  date: string
  actname: string
  actuser: string
  userphone: string
  acttype: string
  status: number
}

const handleImportError = (error: Error) => {
  // 处理导入错误
  console.error('导入失败:', error)
}

// 使用类型化的ref
const tableData = ref<TableData[]>([])

const handleExportSuccess = () => {
  ElMessage.success('导出成功')
}

const handleExportError = (error: Error) => {
  ElMessage.error(`导出失败: ${error.message}`)
}

const handleClear = () => {
  tableData.value = []
}
//跳转设置页面
const linkquestion_bank_cont_setting = function () {
  setTimeout(() => {
    router.push('/question_bank/question_bank_cont_setting')
  }, 0)
}

//搜索刷新等
const search = () => { getData() }
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  searchForm.queryStartTime = ''
  searchForm.queryEndTime = ''
  datavalue1.value = ''
  searchForm.queryCondition = ''
  searchForm.state = ''
}
//弹出层所需的参数和事件
const checked1 = ref(true)
const checked2 = ref(false)
const checked3 = ref(false)
const dialogImageUrl = ref('')
const disabled_banner = ref(false)
const covercont_type = ref(true) //单选框 多选框的判断
const radio = ref('1')

//上传图片
const handlePictureCardPreview_banner = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
//隐藏图片
const handleDownload_banner = (file: UploadFile) => {
  console.log(file)
}
//轮播图部分上传
const handleRemove_banner = (file: UploadFile) => {
  console.log(file)
}
//展示不同的题目类型
const showcovercont_type = function () {
  console.log(covercont_type.value)
  covercont_type.value = !covercont_type.value
}

const isvipshowone = ref(false) //是否vip开关

const cardtype = [
  {
    value: '1',
    label: '已使用'
  },
  {
    value: '2',
    label: '未使用'
  },
  {
    value: '3',
    label: '已过期'
  },
  {
    value: '4',
    label: '已作废'
  }
]
const copyCode = async (text: any) => {
  try {
    console.log(text);
    await navigator.clipboard.writeText(text)
    ElMessage.success('复制成功')
  } catch (err) {
    try {
      const input = document.createElement('input')
      input.value = text
      document.body.appendChild(input)
      input.select()
      document.body.removeChild(input)
      ElMessage('复制成功')
    } catch (e) {
      ElMessage.error('复制失败，请手动复制')
      console.error('复制失败:', e)
    }
  }
}

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}

const openActiveTime = (e: any) => {
  if (e) {
    searchForm.queryStartTime = formatDate(e[0])
    searchForm.queryEndTime = formatDate(e[1])
  } else {
    searchForm.queryStartTime = ''
    searchForm.queryEndTime = ''
  }
  getData()
}

const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
async function getData() {
  try {
    tableLoading.value = true
    const params = filterEmptyValues(searchForm)
    const { code, data } = await cdKeyDetails({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      cdKeyId: queryParams.id,
      ...params
    })
    if (code === '00000' && data) {
      tableData.value = data.list
      pageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}

const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

const downloadQRCode = () => {
  const url = promotionItem.value.qrCode
  if (!url) return
  const a = document.createElement('a')
  a.href = url
  a.download = '推广码.png'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.page-content {
  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }
}

.tag-item+.tag-item {
  margin-left: 5px;
}

.label {
  float: left;
  margin: 0.5rem 0 0.5rem 1.5rem;
  display: inline;
}

.labellist .label:nth-child(1) {
  margin-left: 0;
}

.bankcont_title_text {
  float: left;
  margin-right: 1rem;
}

.label_sonli {
  color: #5d87ff;
}

.cell {
  width: 500px;
}

.tag-item {
  margin-left: 5px;
}

.tagcontsize {
  color: #999;
}

.tagcontbigsize {
  margin-top: 0.5rem;
}

.cartcont {
  margin-top: 0.5rem;
}

.promotion_item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.promotionImg {
  width: 300px;
  height: 300px;
  margin: 20px 0 0px 0;
}

.promotionFont {
  font-size: 18px;
  color: #333;
}

.tips {
  font-weight: 400;
  color: #333;
  margin-top: 20px;
  border-radius: 8px;
  border: 1px solid #60c041;
  font-size: 15px;
  width: 100%;
  height: 40px;
  line-height: 40px;
  background-color: rgba($color: #60c041, $alpha: 0.1);
  padding-left: 20px;
}

.copy {
  color: #5d87ff;
  font-weight: 400;
  cursor: pointer;
}

:deep(.el-dialog__title) {
  font-weight: bold;
  font-size: 20px;
}
</style>
